export default {
    // 简单的同步检测（保持向后兼容）
    checkEnvironment: () => typeof window.cefSharpServer !== 'undefined',
    
    // 增强的异步环境检测，支持延时和重试
    checkEnvironmentAsync: (options = {}) => {
        const {
            maxRetries = 5,        // 最大重试次数
            retryDelay = 500,      // 重试间隔（毫秒）
            initialDelay = 100     // 初始延时（毫秒）
        } = options
        
        return new Promise(resolve => {
            let retryCount = 0
            
            const checkWithRetry = () => {
                // 检测CEFSharp环境
                const isCefSharp = typeof window.cefSharpServer !== 'undefined'
                
                if (isCefSharp) {
                    console.log(`✅ [CEFSharp] 环境检测成功 (尝试 ${retryCount + 1}/${maxRetries + 1})`)
                    resolve({
                        isCefSharp: true,
                        attempts: retryCount + 1,
                        detectedAt: Date.now()
                    })
                    return
                }
                
                // 如果还有重试机会
                if (retryCount < maxRetries) {
                    retryCount++
                    console.log(`⏳ [CEFSharp] 环境检测失败，${retryDelay}ms后重试 (${retryCount}/${maxRetries})`)
                    setTimeout(checkWithRetry, retryDelay)
                } else {
                    console.log(`❌ [CEFSharp] 环境检测失败，已达到最大重试次数 (${maxRetries + 1})`)
                    resolve({
                        isCefSharp: false,
                        attempts: retryCount + 1,
                        detectedAt: Date.now()
                    })
                }
            }
            
            // 初始延时后开始检测
            setTimeout(checkWithRetry, initialDelay)
        })
    },
    
    // 等待CEFSharp环境就绪
    waitForEnvironment: (timeout = 10000) => {
        return new Promise((resolve, reject) => {
            const startTime = Date.now()
            console.log('🔍 [CEFSharp] 等待环境就绪', reject)
            const check = () => {
                if (typeof window.cefSharpServer !== 'undefined') {
                    console.log('✅ [CEFSharp] 环境已就绪')
                    resolve(true)
                    return
                }
                
                const elapsed = Date.now() - startTime
                if (elapsed >= timeout) {
                    console.log(`❌ [CEFSharp] 等待环境超时 (${timeout}ms)`)
                    resolve(false)
                    return
                }
                
                setTimeout(check, 100)
            }
            
            check()
        })
    },
    
    callDbMethod: (methodName, params = {}) =>
        new Promise((resolve, reject) => {
            if (typeof window.cefSharpServer === 'undefined') {
                reject(new Error('CEFSharp环境不可用'))
                return
            }
            try {
                window.cefSharpServer
                    .callDbMethod(methodName, params)
                    .then(resolve)
                    .catch(reject)
            } catch (error) {
                reject(error)
            }
        })
}
